<?php
/**
 * Created by PhpStorm.
 * User: xiong
 * Date: 2017/11/30
 * Time: 08:49
 */


class NewsController extends BaseController
{


    /**
     * 新闻列表接口
     */
    public function listAction()
    {
        $page = $this->getRequest()->getParam('page');
        $is_home = $this->getRequest()->getParam('is_home');
        $page_size = empty($is_home) ? DEFAULT_PAGE_SIZE : getCommonConfig('home_news_num');
        // 条件中的的0理解为没有条件，转换;
        $type = $this->getRequest()->getParam('type') == 0 ? 'ok' : $this->getRequest()->getParam('type');

        $newsM = NewsModel::select(['id', 'theme', 'theme_img', 'type', 'add_time'])
            ->where('status', 1)
            ->when($type, function ($query) use ($type) {
                $type = $type == 'ok' ? '0' : $type;
                return $query->where('type', intval($type));
            });
        $news = $newsM->orderBy('id', 'desc')->paginate($page_size, '', '', $page);
        $data['list'] = $news->items();
        $h5BaseUrl = getCommonConfig('h5_baseurl');
        foreach ($data['list'] as $k => $v) {
            $data['list'][$k]['add_time'] = date("Y-m-d H:i:s", $v['add_time']);
            $data['list'][$k]['url'] = urlencode($h5BaseUrl . "/news/detail?id={$v['id']}");
        }
        $data['page']['lastPage'] = $news->lastPage();
        $data['page']['perPage'] = $news->perPage();
        $data['page']['currentPage'] = $news->currentPage();
        $this->callback($data);
    }

    /**
     * 新闻详情接口
     */
    public function detailAction()
    {
        $id = $this->getRequest()->getParam('id');
        if (empty($id)) {
            $this->callback([], MISS_REQUEST_PARAMS, '缺少参数,参数为空');
        }

        $newsDetail = NewsModel::query()->select('theme', 'content')->where(['id' => $id]);
        $data = $newsDetail->first();

        $this->callback($data);
    }

}